package com.px.user.controller;

import com.px.common.core.RespCode;
import com.px.common.core.Response;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;

/**
 * Replace {@link BasicErrorController}.
 */
@ApiIgnore
@RestController
public class CustomErrorController implements ErrorController {
    private static final String ERROR_PATH = "/error";

    /**
     * Replace {@link BasicErrorController#error)}.
     * @return custom response
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public Response error(HttpServletResponse response){
        if (response.getStatus() == 403)
            return Response.fail(RespCode.FORBIDDEN, null);
        if (response.getStatus() == 400)
            return Response.fail(RespCode.FAIL, null);
        return Response.fail(RespCode.NOT_FOUND, null);
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}
